package com.maxmlr.net.rpc;

import com.google.protobuf.Value;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @ClassName TcpClient
 * @Description TODO
 * @Author maxiao
 * @Date 2020/4/4 下午9:07
 * @Version V1.0
 */
public class TcpClient {

    private String host;
    private int port;

    public TcpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Socket newSocket() {
        Socket socket = null;
        try {
            socket = new Socket(host, port);
            return socket;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Value send(Rpc.RpcRequest rpcRequest) {
        Socket socket = newSocket();
        try {
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(rpcRequest);
            out.flush();

            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            Object result = in.readObject();

            in.close();
            out.close();

            //转化为对象
            return (Value) result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
        return null;
    }
}
